import mysql, { QueryError } from "mysql2";

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT ?? "3306"),
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  // waitForConnections: true,
  // connectionLimit: 10, // 最大连接数
  // queueLimit: 0 // 队列
});

export async function query(sql: string, values?: any[]): Promise<any> {
  return new Promise((resolve, reject) => {
    pool.query(sql, values, (err: QueryError | null, result?: any, fields?: any[]) => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      const columnNames = fields?.map(field => field.name);
      console.log('Column names:', columnNames);
      resolve(result);
    })
  });
}

export default pool;